import React, {useEffect, useState} from 'react'
import { Form, Button, DatePicker,Radio,Upload,Input, Modal,Row,message, Col,Popconfirm,Select} from 'antd'
import { connect } from 'umi'
import moment from 'moment'
import {UploadOutlined} from '@ant-design/icons';
import {getUploadUrl} from '@/utils/upload'
import {evaluationList, jobLevelTypeList} from "@/utils/constant";
import store from 'store2';

const FormItem = Form.Item;
const { TextArea } = Input;
const {Option} = Select;
const RadioGroup = Radio.Group;

const formLayout = {
  labelCol: { span: 7 },
};

const colStyle = {
  xl: 8,
  lg: 8,
  md: 8,
  sm: 8,
  xs: 8,
};

let uploadedFiles = [];

const AddResignForm = (props) => {
  const { onSubmit, onCancel,record, loading,visible,currentUser,global = {} } = props;
  const {options = {}} = global;
  const {jobLevel = []} = options;
  const [form] = Form.useForm();
  const [fileUploadUrls,setFileUploadUrls] = useState([]);
  const [fileName, setFileName] = useState(null);

  const fileList = {
    name: 'file',
    multiple: true,
    action: getUploadUrl(),
    data: {name: fileName},
    defaultFileList: uploadedFiles,
    beforeUpload(file) {
      setFileName(file.name)
    },
    onChange(res) {
      const {status} = res.file;
      if (status === 'done') {
        if (res.file.response.error) {
          message.success(`${res.file.response.error}`);
        } else {
          setFileUploadUrls([...fileUploadUrls,res.file.response ]);
          message.success(`${res.file.name} 文件上传成功`);
        }
      } else if (status === 'error') {
        message.error(`${res.file.name} 文件上传失败`);
      }
    },
    onRemove(info) {
      let urls = fileUploadUrls;
      let index = urls.indexOf(info.response);
      if (index > -1)
        urls.splice(index, 1);
      setFileUploadUrls(urls);
    }
  };

  useEffect(() => {
    if(currentUser){
      let workingEndDate = moment();
      if(visible && record){
        let workingStartTimeDate = moment(record.hiredate);
        form.setFieldsValue({...record,applyTime:moment(record.applyTime),
          hiredate:moment(record.hiredate),dimissionTime:moment(record.dimissionTime),
          workingYears: record.hiredate ? `${workingEndDate.diff(workingStartTimeDate, 'years',true).toFixed(1)}年` : '',
        });
        setFileUploadUrls(record.urlIds ? [record.urlIds] : []);
        if(record.urlIds){
          let fileList = record.urlIds.split(',');
          fileList.forEach((item,index) =>{
            uploadedFiles.push({
              uid: index,
              name: item.split('----')[1],
              status: 'done',
              url: item,
            })
          });
        }
      }else{
        const fieldsValue = store(`personnel-resign-application-` + currentUser.id);
        if(fieldsValue && visible){
          console.log(fieldsValue)
          form.setFieldsValue({...fieldsValue,hiredate:moment(fieldsValue.hiredate),applyTime:moment(fieldsValue.applyTime),
            dimissionTime:moment(fieldsValue.dimissionTime)
          });
          let fileUrlList = fieldsValue.urlIds.split(',');
          setFileUploadUrls(fileUrlList);
          fileUrlList.forEach((item,index) =>{
            uploadedFiles.push({
              uid: index,
              name: item.split('----')[1],
              status: 'done',
              url: item,
            })
          });
        }else{
          let workingStartTimeDate = moment(currentUser.hiredate);
          form.setFieldsValue({applyTime:moment(),...currentUser,
            hiredate: currentUser.hiredate ? moment(currentUser.hiredate) : undefined,
            code:currentUser.usercode,unitname:currentUser.department,jobLevelId:currentUser.jobLevelId+'',
            workingYears: currentUser.hiredate ? `${workingEndDate.diff(workingStartTimeDate, 'years',true).toFixed(1)}年` : '',
          });
        }
      }
    }
  }, [visible]);

  const onFormCancel = () => {
    form.resetFields();
    setFileUploadUrls([]);
    uploadedFiles = [];
    onCancel();
  };

  const handleSubmit = async () => {
    const fieldsValue = await form.validateFields();
    form.resetFields();
    onSubmit({...fieldsValue,urlIdsList:fileUploadUrls,urlIds:'',
      applyCode:currentUser.usercode,applyOid:currentUser.id,applyName:currentUser.name,
      oid:currentUser.id,id:record && record.id
    });
    setFileUploadUrls([]);
    uploadedFiles = [];
  };

  const onFormSave = async () => {
    const fieldsValue = await form.validateFields();
    store(`personnel-resign-application-` + currentUser.id,{...fieldsValue, urlIds: fileUploadUrls && fileUploadUrls.toString()});
    message.success("信息暂存成功！");
  };

  const renderContent = () => {
    return (
      <>
        <Row gutter={24}>
          <Col {...colStyle}>
            <FormItem name="name" label="申请人">
              <Input disabled={true}/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="applyTime" label="申请日期">
              <DatePicker disabled={true} className='widthStyle'/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="code" label="员工工号">
              <Input disabled={true}/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="hiredate" label="入职日期">
              <DatePicker disabled={true} className='widthStyle'/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="unitname" label="所属部门">
              <Input disabled={true}/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="jobname" label="任职岗位">
              <Input disabled={true}/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="jobLevelType" label="职级类型">
              <Select disabled={true}>
                {jobLevelTypeList.map((item, index) => {
                  return (
                    <Option value={item.value} key={item.value}>
                      {item.label}
                    </Option>
                  )
                })}
              </Select>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="jobLevelId" label="职级">
              <Select disabled={true}>
                {
                  jobLevel.map((item, index) => {
                    return (
                      <Option value={item.id} key={item.name}>
                        {item.name}
                      </Option>
                    )
                  })
                }
              </Select>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="dimissionTime" label="离职日期" rules={[{required: true, message: '离职日期不能为空'}]}>
              <DatePicker className='widthStyle'/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="workingYears" label="司龄">
              <Input disabled={true}/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="associate" label="工作接收人" rules={[{required: true, message: '工作接收人不能为空'}]}>
              <Input placeholder="请输入工作交接人"/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="urlIds" labelCol={{span:7}} wrapperCol={{span:17}} label="上传附件" rules={[{required: true, message: '离职附件不能为空'}]}>
              <div style={{display:'flex'}}>
                <Upload {...fileList} className='uploadWidth'>
                  <Button>
                    <UploadOutlined/> 点击上传附件
                  </Button>
                </Upload>
                <a style={{ lineHeight: '32px',width: '60px',marginLeft: '20px' }} href='http://taicaifu.oss-cn-shenzhen.aliyuncs.com/taicaifu/20201014/34d5e8e956654520a77ea491cd5610b6----员工辞职书-模板.docx' target="_blank">模板下载</a>
              </div>
            </FormItem>
          </Col>
          <Col className='settlement-textCenter' span={24}>
            <Row gutter={24}>
              <Col span={24}>
                <FormItem label='项目' className='settlement-title-bg'>评价</FormItem>
              </Col>
              <Col span={24}>
                <FormItem label='主管辅导' name="spervisorCoaching" rules={[{required: true, message: '请选择主管辅导评价'}]}>
                  <RadioGroup>
                    {evaluationList.map((item,index) =>(<Radio key={index} value={item.value}>{item.label}</Radio>))}
                  </RadioGroup>
                </FormItem>
              </Col>

              <Col span={24}>
                <FormItem label='薪资报酬' name="slaryCompensation" rules={[{required: true, message: '请选择薪资报酬评价'}]}>
                  <RadioGroup>
                    {evaluationList.map((item,index) =>(<Radio key={index} value={item.value}>{item.label}</Radio>))}
                  </RadioGroup>
                </FormItem>
              </Col>

              <Col span={24}>
                <FormItem label='工作时间' name="operatingHours" rules={[{required: true, message: '请选择工作时间评价'}]}>
                  <RadioGroup>
                    {evaluationList.map((item,index) =>(<Radio key={index} value={item.value}>{item.label}</Radio>))}
                  </RadioGroup>
                </FormItem>
              </Col>

              <Col span={24}>
                <FormItem label='培训获得' name="trainingObtained" rules={[{required: true, message: '请选择培训获得评价'}]}>
                  <RadioGroup>
                    {evaluationList.map((item,index) =>(<Radio key={index} value={item.value}>{item.label}</Radio>))}
                  </RadioGroup>
                </FormItem>
              </Col>

              <Col span={24}>
                <FormItem label='升迁机会' name="promotionOpportunity" rules={[{required: true, message: '请选择升迁机会评价'}]}>
                  <RadioGroup>
                    {evaluationList.map((item,index) =>(<Radio key={index} value={item.value}>{item.label}</Radio>))}
                  </RadioGroup>
                </FormItem>
              </Col>

              <Col span={24}>
                <FormItem label='沟通渠道' name="communicationChannel" rules={[{required: true, message: '请选择沟通渠道评价'}]}>
                  <RadioGroup>
                    {evaluationList.map((item,index) =>(<Radio key={index} value={item.value}>{item.label}</Radio>))}
                  </RadioGroup>
                </FormItem>
              </Col>
            </Row>
          </Col>
          <Col span={24}>
            <FormItem name="reason" labelCol={{span: 2}} label="离职原因" rules={[{required: true, message: '请输入离职原因'}]}>
              <TextArea rows={4} className='widthStyle'/>
            </FormItem>
          </Col>
        </Row>
      </>
    )
  };

  const renderFooter = () => {
    return (
      <>
        <Button onClick={() => onFormCancel()}>取消</Button>
        <Button onClick={() => onFormSave()}>暂存</Button>
        <Popconfirm title={`是否确认发起离职申请?`}
                    onConfirm={() => handleSubmit()}
                    okText="是"
                    cancelText="否">
          <Button type="primary" loading={loading}>提交</Button>
        </Popconfirm>
      </>
    )
  }

  return (
    <Modal
      maskClosable={false}
      width='75%'
      destroyOnClose
      centered
      title={record ? `编辑离职申请` : `新建离职申请`}
      visible={visible}
      footer={renderFooter()}
      onOk={handleSubmit}
      onCancel={() => onFormCancel()}
      onClose={() => onFormCancel()}
      okText="确认"
      cancelText="取消"
    >
      <Form
        {...formLayout}
        form={form}
        style={{ paddingTop: '24px' }}
      >
        {renderContent()}
      </Form>
    </Modal>
  )
};

export default connect(({global,user}) => ({
  currentUser: user.currentUser,
  global
}))(AddResignForm)
